<!-- 设置奖品页面 -->
<template>
  <view class="bigbox">
    <view style="margin-bottom: 20rpx; text-align: right">
      <u-button size="mini" :disabled="!shopId" @click="handleGoCheck"
        >查看抽奖记录</u-button
      >
    </view>
    <!-- 抽奖功能开关盒子 -->
    <view class="switch-box">
      <view class="switch-label">抽奖功能</view>
      <u-switch
        v-model="isOpen"
        size="50rpx"
        active-color="#4cd964"
        inactive-color="#ccc"
        :disabled="!shopId || !shopName"
        @change="handleSwitchChange"
      ></u-switch>
    </view>

    <!-- 下方内容 - 受开关控制显示 -->
    <view v-if="isOpen">
      <!-- 抽奖说明区域 -->
      <view class="description-box">
        <view class="description-title">抽奖说明</view>
        <view class="description-content">
          <view class="description-item">1.抽奖现场领取奖品，凭手机号兑奖</view>
          <view class="description-item">2.请店铺自行核实中奖人员手机号码</view>
          <view class="description-item">3.下单并支付成功即可抽奖一次</view>
          <view class="description-item"
            >4.需8个奖品均审核通过后抽奖功能才能正常使用</view
          >
          <view class="description-item">
            5.抽奖机会仅限当次消费使用，若不使用则视为自愿放弃该次机会，抽奖资格将自动作废
          </view>
        </view>
      </view>
      <view
        style="
          display: flex;
          justify-content: space-between;
          margin-bottom: 20rpx;
        "
      >
        <view>
          <u-button
            size="mini"
            style="background-color: #aad615; color: white"
            v-if="btnList.length > 1"
            @click="handleGetPrizeList"
            :disabled="isAdd || isEdit"
          >
            获取奖品审核状态
          </u-button>
        </view>
        <view style="margin-bottom: 20rpx; text-align: right">
          <u-button
            size="mini"
            type="success"
            @click="handleAddBtn"
            v-if="btnList.length < 8"
            :disabled="isAdd || isEdit || btnList.length >= 8"
          >
            + 新增奖品
          </u-button>
        </view>
      </view>
      <!-- 按钮区域 -->
      <view class="btns" v-if="btnList.length > 0">
        <view v-for="(ele, index) in btnList" :key="ele.id" class="anbox">
          <u-button
            style="width: 100%"
            :type="currentBtnId == ele.id ? 'primary' : 'default'"
            :class="{ blink: ele.status === 3 }"
            @click="handleClickBtn(ele.id)"
            :disabled="isAdd"
            plain
          >
            {{ ele.name }}
            <u-tag
              :text="getStatusText(ele.status)"
              :type="getStatusType(ele.status)"
              class="status-tag"
            ></u-tag>
          </u-button>
        </view>
      </view>
      <!-- 抽奖设置区域 -->
      <view
        v-if="currentPrizeStatus === 3 && currentPrizeRemark"
        class="reject-reason"
      >
        <u-icon name="error-circle" color="#f56c6c"></u-icon>
        审核不通过原因：<view color="#f56c6c" size="28rpx">{{
          currentPrizeRemark
        }}</view>
      </view>
      <view
        class="content"
        v-if="(btnList.length > 0 && currentBtnId && !isAdd) || isAdd"
      >
        <view class="prize-header">
          <view class="prize-title">
            {{ isAdd ? '新增奖品' : `当前设置的奖品：${currentPrizeText}` }}
          </view>
          <view class="action-btns">
            <view>
              <u-button
                size="mini"
                type="default"
                @click="handleCancelAdd"
                :disabled="isAdd && !canCancel"
                v-if="isAdd"
              >
                取消添加
              </u-button>
              <u-button
                size="mini"
                type="default"
                @click="handleCancelEdit"
                v-else-if="isEdit"
              >
                取消修改
              </u-button>
            </view>
            <view>
              <u-button
                size="mini"
                type="primary"
                @click="handleConfirmAdd"
                v-if="isAdd"
              >
                确认添加
              </u-button>
              <u-button
                size="mini"
                type="primary"
                @click="handleConfirmEdit"
                v-else-if="isEdit"
              >
                确认修改
              </u-button>
              <u-button
                size="mini"
                type="warning"
                @click="handleEditBtn"
                v-else
              >
                编辑
              </u-button>
            </view>
          </view>
        </view>

        <u-form :model="prizeForm" ref="form1">
          <u-form-item label="奖品名称" prop="name" label-width="200rpx">
            <u-input
              clearable
              :border="true"
              placeholder="不超过7个字"
              v-model="prizeForm.name"
              :disabled="!isEdit && !isAdd"
              maxlength="7"
            />
          </u-form-item>
          <u-form-item label="设置数量" prop="totalCount" label-width="200rpx">
            <u-input
              clearable
              :border="true"
              placeholder="可抽的总个数，为0不会中"
              v-model.number="prizeForm.totalCount"
              type="number"
              :disabled="!isEdit && !isAdd"
            />
          </u-form-item>
          <u-form-item label="剩余数量" prop="count" label-width="200rpx">
            <u-input
              clearable
              :border="true"
              v-model.number="prizeForm.count"
              type="number"
              :disabled="true"
            />
          </u-form-item>
          <view class="tsbox">中奖条件</view>
          <u-form-item
            label="每营收金额"
            prop="limitMoney"
            label-width="200rpx"
          >
            <u-input
              clearable
              :border="true"
              placeholder="指营收每满多少可以中奖"
              v-model.number="prizeForm.limitMoney"
              type="number"
              :disabled="!isEdit && !isAdd"
            />
          </u-form-item>
          <u-form-item
            label="用户消费金额"
            prop="limitUserMoney"
            label-width="200rpx"
          >
            <u-input
              clearable
              :border="true"
              placeholder="累计消费金额"
              v-model.number="prizeForm.limitUserMoney"
              type="number"
              :disabled="!isEdit && !isAdd"
            />
          </u-form-item>
          <u-form-item
            label="抽奖人数满多少人必中"
            prop="limitCount"
            label-width="300rpx"
          >
            <u-input
              clearable
              :border="true"
              placeholder="满多少人抽中"
              v-model.number="prizeForm.limitCount"
              type="number"
              :disabled="!isEdit && !isAdd"
            />
          </u-form-item>
        </u-form>
      </view>
      <view class="empty-tip" v-else-if="btnList.length > 0">
        请选择一个奖品
      </view>
      <view class="empty-tip" v-else> 请点击"新增奖品"添加第一个奖品 </view>
    </view>

    <!-- 开关关闭时的提示 -->
    <view class="disabled-tip" v-else> 抽奖功能已关闭，请开启后进行操作 </view>
  </view>
</template>

<script setup lang="ts">
import { reactive, ref, computed } from 'vue'
import { onLoad } from '@dcloudio/uni-app'
import { couponApi } from '@/api'

// 类型定义
interface IBtnInterface {
  id: string
  name: string
  status: number // 1:审核中 2:审核通过 3:审核不通过
  totalCount: number
  count: number
  limitMoney: number
  limitUserMoney: number
  limitCount: number
  remark: string
}

interface IPrizeInterface {
  name: string
  totalCount: number
  count: number
  limitMoney: number
  limitUserMoney: number
  limitCount: number
  remark: string
}

// 状态管理
const shopId = ref('')
const drawPrizeId = ref('')
const shopName = ref('')
const isOpen = ref(false)
const btnList = ref<IBtnInterface[]>([])
const prizeDataMap = ref<Record<string, IBtnInterface>>({})
const currentBtnId = ref('')
const isEdit = ref(false)
const isAdd = ref(false)
const canCancel = ref(true)

// 表单数据
const prizeForm = reactive<IPrizeInterface>({
  name: '',
  totalCount: 0,
  count: 0,
  limitMoney: 0,
  limitUserMoney: 0,
  limitCount: 0,
  remark: ''
})

// 生命周期：获取商家ID
onLoad(async (option: any) => {
  console.log('抽奖设置Option', option)
  shopId.value = option.shopId || ''
  shopName.value = option.shopName || ''

  if (!shopId.value) {
    uni.showToast({ title: '缺少商家id', icon: 'none' })
    return
  }
  if (!shopName.value) {
    uni.showToast({ title: '缺少商家名称', icon: 'none' })
    return
  }

  await handleGetOpenStatus()
  await handleGetPrizeList()
})

// 当前选中奖品文本
const currentPrizeText = computed(() => {
  const currentPrize = btnList.value.find(
    (item) => item.id === currentBtnId.value
  )
  return currentPrize?.name || ''
})
const currentPrizeStatus = computed(() => {
  return prizeDataMap.value[currentBtnId.value]?.status || 0
})
const currentPrizeRemark = computed(() => {
  return prizeDataMap.value[currentBtnId.value]?.remark || ''
})
// 获取抽奖功能开关状态
const handleGetOpenStatus = async () => {
  try {
    const { data } = await couponApi.handleGetDrawOpenStatusApi({
      shopId: shopId.value
    })
    if (data) {
      drawPrizeId.value = data.id
      isOpen.value = data.status === 1
    } else {
      isOpen.value = false
    }
  } catch (error) {
    console.error('获取状态失败', error)
  }
}

// 获取奖品列表
const handleGetPrizeList = async () => {
  uni.showLoading({ title: '加载中，请稍后', mask: true })
  try {
    const { data } = await couponApi
      .handleGetPrizeListAPi({
        turntableId: drawPrizeId.value,
        shopId: shopId.value
      })
      .finally(() => {
        uni.hideLoading()
      })

    if (data.records.length > 0) {
      btnList.value = data.records.map((item: any) => ({
        id: item.id,
        name: item.name,
        status: item.status, // 直接使用接口返回的status
        totalCount: item.totalCount,
        count: item.count,
        limitMoney: item.limitMoney,
        limitUserMoney: item.limitUserMoney,
        limitCount: item.limitCount,
        remark: item.remark
      }))

      // 更新数据映射表
      btnList.value.forEach((prize) => {
        prizeDataMap.value[prize.id] = prize
      })

      // 默认选中第一个奖品
      currentBtnId.value = btnList.value[0].id
      // 同步第一个奖品数据到prizeForm
      const firstPrize = prizeDataMap.value[currentBtnId.value]
      if (firstPrize) {
        Object.assign(prizeForm, {
          name: firstPrize.name,
          totalCount: firstPrize.totalCount,
          count: firstPrize.count,
          limitMoney: firstPrize.limitMoney,
          limitUserMoney: firstPrize.limitUserMoney,
          limitCount: firstPrize.limitCount
        })
      }
    }
  } catch (error) {
    console.error('获取奖品列表失败', error)
  }
}

// 改变抽奖功能开关状态
const handleChangeOpenStatu = async (zt: boolean) => {
  try {
    await couponApi.handleUpDrawOpenStatusApi({
      id: drawPrizeId.value,
      shopId: shopId.value,
      name: shopName.value,
      status: zt ? 1 : 0
    })
  } catch (error) {
    console.error('改变状态失败', error)
  }
  handleGetOpenStatus()
}

// 状态文本转换
const getStatusText = (status: number) => {
  switch (status) {
    case 1:
      return '审核中'
    case 2:
      return '审核通过'
    case 3:
      return '审核不通过'
  }
}

// 状态标签类型
const getStatusType = (status: number) => {
  switch (status) {
    case 1:
      return 'warning'
    case 2:
      return 'success'
    case 3:
      return 'error'
    default:
      return 'info'
  }
}

// 按钮类型
const getBtnType = (status: number) => {
  switch (status) {
    case 1:
      return 'default'
    case 2:
      return 'success'
    case 3:
      return 'error'
    default:
      return 'default'
  }
}

// 开关状态变化
const handleSwitchChange = async (val: boolean) => {
  handleChangeOpenStatu(val)
}

// 点击奖品按钮
const handleClickBtn = (id: string) => {
  if (isAdd.value) {
    uni.showToast({ title: '请先完成当前新增操作', icon: 'none' })
    return
  }

  if (isEdit.value) {
    uni.showModal({
      title: '提示',
      content: '当前有未保存的修改，是否放弃？',
      success: (res) => res.confirm && handleSwitchPrize(id)
    })
    return
  }

  handleSwitchPrize(id)
}

// 切换奖品
const handleSwitchPrize = (id: string) => {
  currentBtnId.value = id
  const currentPrizeData = prizeDataMap.value[id]
  if (currentPrizeData) {
    Object.assign(prizeForm, {
      name: currentPrizeData.name,
      totalCount: currentPrizeData.totalCount,
      count: currentPrizeData.count,
      limitMoney: currentPrizeData.limitMoney,
      limitUserMoney: currentPrizeData.limitUserMoney,
      limitCount: currentPrizeData.limitCount
    })
  } else {
    Object.assign(prizeForm, {
      name: '',
      totalCount: 0,
      count: 0,
      limitMoney: 0,
      limitUserMoney: 0,
      limitCount: 0
    })
  }

  isEdit.value = false
}

// 验证表单
const validateForm = (): boolean => {
  if (!prizeForm.name?.trim()) {
    uni.showToast({ title: '请输入奖品名称', icon: 'none' })
    return false
  }
  if (prizeForm.totalCount <= 0) {
    uni.showToast({ title: '奖品数量必须大于0', icon: 'none' })
    return false
  }
  // if (prizeForm.limitMoney <= 0) {
  //   uni.showToast({ title: '营收金额必须大于0', icon: 'none' })
  //   return false
  // }
  // if (prizeForm.limitUserMoney <= 0) {
  //   uni.showToast({ title: '消费金额必须大于0', icon: 'none' })
  //   return false
  // }
  // if (prizeForm.limitCount <= 0) {
  //   uni.showToast({ title: '必中人数必须大于0', icon: 'none' })
  //   return false
  // }
  return true
}

// 点击新增按钮
const handleAddBtn = () => {
  if (btnList.value.length >= 8) {
    uni.showToast({ title: '最多只能新增8个奖品', icon: 'none' })
    return
  }
  isAdd.value = true
  Object.assign(prizeForm, {
    name: '',
    totalCount: 0,
    count: 0,
    limitMoney: 0,
    limitUserMoney: 0,
    limitCount: 0
  })
  currentBtnId.value = ''
}

// 确认新增按钮
const handleConfirmAdd = async () => {
  if (!validateForm()) return
  if (btnList.value.length >= 8) return

  canCancel.value = false
  try {
    const tempObj = {
      ...prizeForm,
      shopId: shopId.value,
      shopName: shopName.value,
      turntableId: drawPrizeId.value,
      status: 1 // 新增奖品默认审核中状态
    }

    const { data, code } = await couponApi.handleAddPrizeApi(tempObj)
    if (code === 200) {
      uni.showToast({ title: '新增成功', icon: 'success' })
      const newPrize = {
        id: data.id,
        status: 1, // 新增默认为审核中
        ...prizeForm
      }
      btnList.value.push(newPrize)
      prizeDataMap.value[data.id] = newPrize
      handleSwitchPrize(data.id)
      isAdd.value = false
    }
  } catch (error) {
    uni.showToast({ title: '新增失败', icon: 'none' })
  } finally {
    canCancel.value = true
  }
}

// 取消新增按钮
const handleCancelAdd = () => {
  isAdd.value = false
  if (btnList.value.length > 0) {
    currentBtnId.value = btnList.value[0].id
    const currentPrize = prizeDataMap.value[currentBtnId.value]
    if (currentPrize) {
      Object.assign(prizeForm, {
        name: currentPrize.name,
        totalCount: currentPrize.totalCount,
        count: currentPrize.count,
        limitMoney: currentPrize.limitMoney,
        limitUserMoney: currentPrize.limitUserMoney,
        limitCount: currentPrize.limitCount
      })
    }
  } else {
    currentBtnId.value = ''
  }
}

// 点击编辑按钮
const handleEditBtn = () => {
  isEdit.value = true
}

// 确认修改按钮
const handleConfirmEdit = async () => {
  if (!validateForm()) return

  try {
    const tempObj = {
      ...prizeForm,
      id: currentBtnId.value,
      shopId: shopId.value,
      shopName: shopName.value,
      turntableId: drawPrizeId.value,
      status: 1 // 编辑后重置为审核中状态
    }

    const { data, code } = await couponApi.handleUpPrizeApi(tempObj)
    if (code === 200) {
      uni.showToast({ title: '修改成功', icon: 'success' })

      // 更新本地数据
      if (currentBtnId.value) {
        const updatedPrize = {
          ...prizeDataMap.value[currentBtnId.value],
          ...prizeForm,
          status: 1 // 编辑后状态改为审核中
        }
        prizeDataMap.value[currentBtnId.value] = updatedPrize

        // 更新按钮列表
        const btnIndex = btnList.value.findIndex(
          (item) => item.id === currentBtnId.value
        )
        if (btnIndex > -1) {
          btnList.value[btnIndex] = updatedPrize
        }
      }

      isEdit.value = false
      // 重新获取最新列表数据
      await handleGetPrizeList()
    }
  } catch (error) {
    uni.showToast({ title: '修改失败', icon: 'none' })
  }
}

// 取消修改按钮
const handleCancelEdit = () => {
  const currentPrize = prizeDataMap.value[currentBtnId.value]
  if (currentPrize) {
    Object.assign(prizeForm, {
      name: currentPrize.name,
      totalCount: currentPrize.totalCount,
      // count: currentPrize.count,
      limitMoney: currentPrize.limitMoney,
      limitUserMoney: currentPrize.limitUserMoney,
      limitCount: currentPrize.limitCount
    })
  } else {
    Object.assign(prizeForm, {
      name: '',
      totalCount: 0,
      count: 0,
      limitMoney: 0,
      limitUserMoney: 0,
      limitCount: 0
    })
  }
  isEdit.value = false
}
// 跳转查看中奖记录页面
const handleGoCheck = () => {
  uni.navigateTo({ url: `/pages/drawPrize/prizeRecord?shopId=${shopId.value}` })
}
</script>

<style lang="scss" scoped>
/* 高亮闪烁动画 */
@keyframes blink {
  0% {
    opacity: 1;
  }
  50% {
    opacity: 0.3;
  }
  100% {
    opacity: 1;
  }
}

.blink {
  animation: blink 1s infinite;
}

/* 状态标签样式 */
.status-tag {
  margin-left: 8rpx;
  font-size: 20rpx;
}

/* 原有样式保持不变 */
.bigbox {
  font-size: 24rpx;
  padding: 20rpx;
  background-color: #f5f5f5;
  min-height: 100vh;
}

.switch-box {
  background-color: #fff;
  padding: 25rpx 20rpx;
  border-radius: 10rpx;
  margin-bottom: 20rpx;
  display: flex;
  justify-content: space-between;
  align-items: center;

  .switch-label {
    font-size: 28rpx;
    color: #333;
    font-weight: 500;
  }
}

.description-box {
  background-color: #fff;
  padding: 20rpx;
  border-radius: 10rpx;
  margin-bottom: 20rpx;
  border-left: 4rpx solid #4cd964;

  .description-title {
    font-size: 28rpx;
    font-weight: bold;
    color: #333;
    margin-bottom: 15rpx;
  }

  .description-content {
    font-size: 24rpx;
    color: #666;
    line-height: 1.6;

    .description-item {
      margin-bottom: 10rpx;
      position: relative;
      padding-left: 30rpx;

      &:before {
        content: '';
        position: absolute;
        left: 10rpx;
        top: 16rpx;
        width: 6rpx;
        height: 6rpx;
        border-radius: 50%;
        background-color: #666;
      }
    }
  }
}

.btns {
  background-color: #fff;
  margin-bottom: 20rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  flex-wrap: wrap;
  padding: 20rpx;
  border-radius: 10rpx;
  .anbox {
    width: 99%;
    margin-bottom: 20rpx;
  }
}

.content {
  background-color: #fff;
  padding: 20rpx;
  border-radius: 10rpx;

  .prize-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 15rpx 0;
    margin-bottom: 20rpx;
    border-bottom: 1px solid #eee;

    .prize-title {
      font-size: 28rpx;
      font-weight: 500;
      color: #34b8ed;
      font-weight: bold;
    }

    .action-btns {
      display: flex;
      gap: 15rpx;
    }
  }

  .tsbox {
    font-size: 35rpx;
    font-weight: bold;
    height: 80rpx;
    line-height: 80rpx;
    margin: 10rpx 0;
    color: #333;
  }

  ::v-deep .u-input--disabled {
    background-color: #f9f9f9;
    color: #999;
    border-color: #eee;
  }

  ::v-deep .u-form-item__label:before {
    content: '*';
    color: #ff3333;
    margin-right: 4rpx;
  }
}

.empty-tip,
.disabled-tip {
  background-color: #fff;
  padding: 60rpx 20rpx;
  border-radius: 10rpx;
  text-align: center;
  color: #999;
  font-size: 28rpx;
  margin-top: 20rpx;
}

.disabled-tip {
  color: #f56c6c;
  background-color: #fff8f8;
}
.reject-reason {
  margin-top: 20rpx;
  padding: 15rpx;
  background-color: #fff8f8;
  border-left: 3rpx solid #f56c6c;
  font-size: 28rpx;
  display: flex;
  align-items: center;
  gap: 10rpx;
}
::v-deep .u-button {
  width: 50%;
}
::v-deep .u-btn--primary--plain[data-v-034b34b2] {
  color: #187fff !important;
  border-color: #a0cfff !important;
  background-color: #ecf5ff !important;
}
::v-deep .uni-input-input:disabled {
  background-color: #eee !important;
  border-color: #e0e0e0 !important;
}
</style>
